import { useMemo } from "react";
import { URLSearchParamsInit, useSearchParams } from "react-router-dom";
import { cleanObject } from "utils";

//返回页面url参数中，指定键的值
export const useUrlQueryParam = <K extends string>(keys: K[]) => {
  const [searchParams, setSearchParams] = useSearchParams(); //searchParams不能直接读取参数，要用get方法
  return [
    useMemo(
      () => keys.reduce(
      (prev: { [key in K]: string }, key: K) => {
        return { ...prev, [key]: searchParams.get(key) || "" };
      },
      {} as { [key in K]: string },
    )
      , [searchParams]),
    //setSearchParams,
    (params: Partial<{[key in K]: unknown}>) => {
      const o = cleanObject({...Object.fromEntries(searchParams), ...params}) as URLSearchParamsInit
      setSearchParams(o) //搜索框中的搜索条件可以更新在url的查询参数列表中
    }
  ] as const;
};
